package com.newland.starpos.partner.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newland.starpos.partner.utils.GenerateUtils;
import com.newland.starpos.partner.exception.CustomException;
import com.newland.starpos.partner.http.ResponseEnum;
import com.newland.starpos.partner.http.ResponseModel;
import com.newland.starpos.partner.http.SmsTemplate;
import com.newland.starpos.partner.service.function.RedisCache;
import com.newland.starpos.partner.utils.HttpUtils;
import com.newland.starpos.partner.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class AuthCodeService {

    private static final Logger logger = LoggerFactory.getLogger(AuthCodeService.class);

	private static final String smsurl = "http://api.starpos.com.cn:8080/cloudpos/sms/singleSendSms";

    private static final String PARTNER_AUTH_CODE = "PT_AUTH_";

    @Autowired
    private RedisCache redisCache;

    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @param type
     * @return {"code": 0,"message": "OK"}
     */
    public ResponseModel sendAuthCode(String phoneNumber, int type) throws CustomException {

        String code = GenerateUtils.getAuthCode();
        String templateCode = SmsTemplate.getSmsTemplateCode(type);
        if (StringUtils.isBlank(templateCode)) {
            throw new CustomException(ResponseEnum.SMS_TYPE_ERROR);
        }

        String content = buildCodeSms(templateCode, phoneNumber, code);
        String response;
        try {
            response = HttpUtils.postJsonU8(smsurl, content);
        } catch (Exception e) {
            logger.info("短信发送请求异常，异常信息：{}", e.getMessage());
            throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信发送请求异常");
        }
        if (StringUtils.isBlank(response)) {
            logger.info("短信服务返回异常，响应内容为空.");
            throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信服务返回异常");
        }

        // 解析返回结果
        JSONObject resp = JSON.parseObject(response);// 解析返回结果
        String respCode = (String) resp.get("code");// 获取响应码

        // 返回结果处理
        switch (respCode) {
            case "success":
                JSONObject data = (JSONObject) resp.get("data");
                String requestId = data.getString("RequestId");
                redisCache.setString(PARTNER_AUTH_CODE + phoneNumber, code, 30, TimeUnit.MINUTES);
                break;
            case "failure":
                throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), resp.getString("message"));
            default:
                throw new CustomException(ResponseEnum.SMS_SERVER_ERROR.code(), "短信发送响应码不正确");
        }
        return new ResponseModel(ResponseEnum.OK);
    }

    /**
     * 检验手机验证码
     * @return code和redis里一致返回true, 其他返回false
     */
    public boolean checkAuthCode(String phoneNumber, String code) {
        Objects.requireNonNull(code, "验证码不能为空");
        String redisCode = redisCache.getString(PARTNER_AUTH_CODE + phoneNumber);
        logger.info("redis取出验证码,phoneNumber:[{}],code[{}]", phoneNumber, redisCode);
        if (StringUtils.equals(code, redisCode))
            return true;
        return false;
    }

    /**
     * @param templateCode
     * @param mobile
     * @param code
     * @return 组装过后的json字符串
     */
    public String buildCodeSms(String templateCode, String mobile, String code) {
        JSONObject request = new JSONObject();
        JSONObject paramstring = new JSONObject();
        paramstring.put("code", code);
        request.put("paramstring", paramstring);
        request.put("recnum", mobile);
        request.put("signname", "新大陆");
        request.put("templatecode", templateCode);
        return request.toJSONString();
    }

}